import { useEffect } from "react"
import { Platform } from "react-native"
import { router } from "expo-router"
import * as Burnt from "burnt"
import {
  finishTransaction,
  purchaseErrorListener,
  purchaseUpdatedListener,
  useIAP,
} from "react-native-iap"

import { translate } from "@/i18n"
import { useStores } from "@/models/helpers/useStores"
import { verifyIAPAppStoreTransaction } from "@/services/api/order"

export const useInitIAP = (configInit?: boolean) => {
  const { userStore, configStore, systemStore } = useStores()
  useIAP({
    onPurchaseSuccess: async (purchase) => {
      try {
        // console.log("Purchase successful:", purchase)
        // 1) 标记完成交易，避免重复触发 / "Duplicate purchase update" 问题

        verifyIAPAppStoreTransaction({
          transactionId: purchase.transactionId,
        })
          .then((res: any) => {
            // console.log("IAP Data verifyIAPAppStoreTransaction: ", res?.data?.code)
            if ([200, 1202, 1201, 1104, 1106].includes(res?.data?.code)) {
              finishTransaction({
                purchase,
                isConsumable: true,
              }).then((res) => {
                console.log("finishTransaction result:", res)
                userStore.fetchProfile()
                systemStore.hideModal()
              })
            } else {
              console.error(
                "IAP Data verifyIAPAppStoreTransaction error: ",
                res.data,
                // currentPurchase,
              )
              systemStore.hideModal()
            }
          })
          .catch((err) => {
            systemStore.hideModal()

            console.warn("IAP Data verifyIAPAppStoreTransaction warn: ", err)
          })

        // 2) 成功提示并刷新/返回
        Burnt.alert({
          title: translate("pay:purchaseSuccess"),
          preset: "done",
          duration: 1,
        })
        // 根据你的业务需要刷新用户信息
        // userStore.getUserInfo()

        // 4) 关闭当前页面
        // router.back()
      } catch (e) {
        console.warn("onPurchaseSuccess follow-up failed:", e)
        systemStore.hideModal()
      }
    },
    onPurchaseError: (error) => {
      // console.error("Purchase failed:", error)
      Burnt.toast({
        preset: "error",
        title: error?.message,
      })
      systemStore.hideModal()

      // Handle purchase error
    },
  })

  useEffect(() => {
    const purchaseUpdateSubscription = purchaseUpdatedListener((purchase) => {
      // console.log("purchase update", purchase)
    })

    const purchaseErrorSubscription = purchaseErrorListener((error) => {
      console.log("error", error)
    })

    return () => {
      purchaseUpdateSubscription?.remove()
      purchaseErrorSubscription?.remove()
    }
  }, [])

  /*useEffect(() => {
    /!*   currentPurchase &&
      finishTransaction({
        purchase: currentPurchase,
        isConsumable: false,
      }).then((res) => {
        // console.log("IAP Data finishTransaction: ", res)
      }) *!/
    if (currentPurchase && currentPurchase.transactionReceipt && Platform.OS === "ios") {
      console.log("IAP Data currentPurchase: ", currentPurchase)
      // if (currentPurchase.productId.includes("renewable")) {
      //   finishTransactionHandler(currentPurchase, userStore)
      // } else {
      verifyIAPAppStoreTransaction({
        transactionId: currentPurchase.transactionId,
      })
        .then((res: any) => {
          // console.log("IAP Data verifyIAPAppStoreTransaction: ", res?.data?.code)
          if ([200, 1202, 1201, 1104, 1106].includes(res?.data?.code)) {
            finishTransactionHandler(currentPurchase, userStore)
          } else {
            console.error(
              "IAP Data verifyIAPAppStoreTransaction error: ",
              res.data,
              // currentPurchase,
            )
          }
        })
        .catch((err) => {
          console.warn("IAP Data verifyIAPAppStoreTransaction warn: ", err)
        })
      // }
    }

    // ... listen to currentPurchase, to check if the purchase went through
  }, [currentPurchase])*/
}
